package com.qf.flash.ui.mine;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.Constant;
import com.qf.flash.event.ChangeGroupEvent;
import com.qf.flash.http.response.GameDetailResponse;
import com.qf.flash.http.response.ScriptDetailResponse;
import com.qf.flash.model.CommentBean;
import com.qf.flash.model.ScriptRoleBean;
import com.qf.flash.mvp.contract.CommentContract;
import com.qf.flash.mvp.contract.GameDetailContract;
import com.qf.flash.mvp.contract.InsertResponseContract;
import com.qf.flash.mvp.contract.ScriptDetailContract;
import com.qf.flash.mvp.presenter.CommentPresenter;
import com.qf.flash.mvp.presenter.GameDetailPresenter;
import com.qf.flash.mvp.presenter.InsertResponsePresenter;
import com.qf.flash.mvp.presenter.ScriptDetailPresenter;
import com.qf.flash.ui.chat.ChatActivity;
import com.qf.flash.ui.home.BusinessDetailActivity;
import com.qf.flash.ui.home.ChoseBusinessActivity;
import com.qf.flash.ui.home.MemberMsgActivity;
import com.qf.flash.ui.home.RolePagerActivity;
import com.qf.flash.ui.home.adapter.GameCommentView;
import com.qf.flash.ui.home.adapter.GroupMemberItem;
import com.qf.flash.ui.home.adapter.RoleItem;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.widget.RatingBarView;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.util.SpannableStringUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.text.Html.FROM_HTML_MODE_COMPACT;
import static com.qf.flash.constant.Constant.INVITER;
import static com.qf.flash.constant.Constant.PINGJIA;
import static com.qf.flash.constant.FlashCodes.PLAY_WOLF_KILL;

/**
 * 游戏详情Activity
 */
public class GameDetailsActivity extends BaseActivity implements GameDetailContract.View, CommentContract.View, ScriptDetailContract.View, InsertResponseContract.View {
    @BindView(R.id.tv_top_back)
    TextView tvTopBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_title)
    TextView tvName;
    @BindView(R.id.tv_group_no)
    TextView tvGroupNo;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_bus_name)
    TextView tvBusName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.iv_open_close)
    ImageView ivOpenClose;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvSHopName;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.tv_members)
    TextView tvMembers;
    @BindView(R.id.rv_members)
    RecyclerView rvMembers;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.rbv_star)
    RatingBarView rbvStar;
    @BindView(R.id.tv_total_comment)
    TextView tvTotalComment;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.tv_role_title)
    TextView tv_role_title;
    @BindView(R.id.rv_role)
    RecyclerView rvRole;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.tv_empty_place)
    TextView tv_empty_place;
    @BindView(R.id.group_business_msg)
    Group group_business_msg;
    @BindView(R.id.in_juben)
    ConstraintLayout cl_comment;
    @BindView(R.id.tv_gon_chat)
    TextView tvGonChat;
    private RVAdapter<ScriptRoleBean> mRoleAdapter;
    private GameDetailPresenter gameDetailPresenter;
    private InsertResponsePresenter insertResponsePresenter;
    private ScriptDetailPresenter mScriptDetailPresenter;
    private CommentPresenter commentPresenter;
    private boolean isOpen;
    private RVAdapter<Object> mMemberAdapter;
    private int page = 1;
    private RVAdapter<Object> mCommentAdapter;
    private String status, type;
    private Dialog judgeDialog, scoreDialog, inviteDialog;
    private TextView tv_judge_shop, tv_judge_juben, tv_judge_cancel, tv_judge_sure;
    private GameDetailResponse gameDetailBean;
    private Drawable check;
    private Drawable uncheck;
    private EditText editText;
    private RatingBarView star;
    private TextView tv_score_cancel, tv_score_sure;
    private ArrayList<GameDetailResponse.UsersBean> users;
    private String playId;
    private String id;// 订单id


    @Override
    protected int getLayoutId() {
        return R.layout.activity_game_detail;
    }

    @Override
    protected void initInject() {
        super.initInject();
        gameDetailPresenter = new GameDetailPresenter();
        commentPresenter = new CommentPresenter();
        insertResponsePresenter = new InsertResponsePresenter();
        mScriptDetailPresenter = new ScriptDetailPresenter();
        initPresenters(gameDetailPresenter, commentPresenter, insertResponsePresenter, mScriptDetailPresenter);
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("组队详情");
        initMemberRv();
        initCommentRv();
        initRvRole();
        id = getIntent().getStringExtra("id");
        playId = getIntent().getStringExtra("playId");
        status = getIntent().getStringExtra("status");
        type = getIntent().getStringExtra("type");
        if (status.equals(PINGJIA)) {
            tvJoin.setText("发表评价");
        } else if (status.equals(INVITER)) {
            tvJoin.setText("邀请好友");
        } else {
            tvJoin.setVisibility(View.GONE);
        }


        gameDetailPresenter.getGameDetail(id);
        if (TextUtils.isEmpty(playId)) {
            mRefresh.setEnableRefresh(false);
            mRefresh.setEnableLoadMore(false);
            cl_comment.setVisibility(View.GONE);
            mRefresh.setEnableLoadMore(false);
        } else {
            commentPresenter.getCommentData(playId, page);
        }
        initShowMode();
        initJudgeDialog();
        initScoreDialog();
        initInviteDialog();


    }

    /**
     * 邀请好友dialog
     */
    private void initInviteDialog() {
        inviteDialog = new Dialog(this, R.style.custom_dialog2);
    }

    /**
     * 五星打分  dialog
     */
    private void initScoreDialog() {
        scoreDialog = new Dialog(this, R.style.custom_dialog2);

        Window window = scoreDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        View v = View.inflate(this, R.layout.dialog_score, null);
        window.setContentView(v);
        scoreDialog.setCanceledOnTouchOutside(false);
        WindowManager.LayoutParams p = window.getAttributes();
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay();
        p.width = (int) (d.getWidth() * 0.82);
        p.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(p);

        editText = v.findViewById(R.id.et_content);
        star = v.findViewById(R.id.rbv_star);
        tv_score_cancel = v.findViewById(R.id.tv_cancel);
        tv_score_sure = v.findViewById(R.id.tv_submit);

        star.setOnRatingListener(new RatingBarView.OnRatingListener() {
            @Override
            public void onRating(Object bindObject, int RatingScore) {
                star.setStar(RatingScore, false);

            }
        });

        tv_score_cancel.setOnClickListener(view -> {
            scoreDialog.dismiss();
        });

        tv_score_sure.setOnClickListener(view -> {
            if (jubenCheck[0])
                insertResponsePresenter.submitPlayDatas(playId, editText.getText().toString(), (float) star.getStarCount(), id);
            if (shopCheck[0])
                insertResponsePresenter.submitShopDatas(gameDetailBean.getShopId(), editText.getText().toString(), (float) star.getStarCount(), id);
        });
        scoreDialog.setOnShowListener(dialog -> {
            star.setStar(0, false);
            editText.setText("");
        });
    }

    /**
     * 评价dialog    商家or剧本
     */
    private void initJudgeDialog() {
        judgeDialog = new Dialog(this, R.style.custom_dialog2);

        Window window = judgeDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        View v = View.inflate(this, R.layout.dialog_shop_or_script, null);
        window.setContentView(v);
        judgeDialog.setCanceledOnTouchOutside(false);
        WindowManager.LayoutParams p = window.getAttributes();
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay();
        p.width = (int) (d.getWidth() * 0.82);
        p.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(p);
        tv_judge_shop = v.findViewById(R.id.tv_shop);
        tv_judge_juben = v.findViewById(R.id.tv_juben);
        tv_judge_sure = v.findViewById(R.id.tv_pay);
        tv_judge_cancel = v.findViewById(R.id.tv_cancel);
        if (TextUtils.isEmpty(playId)) {
            tv_judge_juben.setVisibility(View.GONE);
        }

        check = getResources().getDrawable(R.mipmap.icon_check);
        uncheck = getResources().getDrawable(R.mipmap.icon_uncheck);
        check.setBounds(0, 0, check.getMinimumWidth(), check.getMinimumHeight());
        uncheck.setBounds(0, 0, uncheck.getMinimumWidth(), uncheck.getMinimumHeight());

    }

    // 控制ui展示
    private void initShowMode() {
        // 故事简介
        View introduce = findViewById(R.id.in_introduce);
        // 商家信息
        View shop = findViewById(R.id.in_shop);
        //  剧本  in_juben
        View juben = findViewById(R.id.in_juben);
        if (status.equals(PINGJIA)) {
            introduce.setVisibility(View.VISIBLE);
            tvShop.setVisibility(View.VISIBLE);
            shop.setVisibility(View.VISIBLE);
            juben.setVisibility(View.VISIBLE);
            rvComment.setVisibility(View.VISIBLE);
        } else if (status.equals(INVITER)) {
        }
        if (type.equals(PLAY_WOLF_KILL)) {
            introduce.setVisibility(View.GONE);
            juben.setVisibility(View.GONE);
            rvComment.setVisibility(View.GONE);
        }
    }

    public static void start(Context activity, String id, String playId, String status, String type) {
        Intent intent = new Intent(activity, GameDetailsActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("playId", playId);
        intent.putExtra("status", status);
        intent.putExtra("type", type);
        activity.startActivity(intent);
    }


    @OnClick({R.id.tv_top_back, R.id.iv_open_close, R.id.tv_join, R.id.in_shop, R.id.tv_gon_chat})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_top_back:

                finish();
                break;
            case R.id.iv_open_close:
                onArrowClick();
                break;
            case R.id.tv_gon_chat:
                ChatActivity.goGroupChat(this, Constant.CHATTYPE_GROUP, gameDetailBean.getEmchatId());
                break;
            case R.id.tv_join:
                switch (status) {
                    case PINGJIA:
                        if (gameDetailBean.getResponsePlay() != 0 && gameDetailBean.getResponseShop() != 0) {
                            FlashLib.showToast("已发表过评论");
                        } else if (TextUtils.isEmpty(playId) && gameDetailBean.getResponseShop() != 0) {
                            FlashLib.showToast("已发表过评论");
                        } else {
                            judgeDialogShow();
                        }
                        break;
                    case INVITER:
                        if (gameDetailBean == null)
                            return;
                        //加入组队
                        if (gameDetailBean.getNeedNum() == gameDetailBean.getPayedNum()) {
                            FlashLib.showToast("人员已满, 暂不能邀请好友");
                            return;
                        }
                        String orderState = gameDetailBean.getOrderState();
                        if (Integer.parseInt(orderState) >= 2) {
                            FlashLib.showToast("已完成组队, 暂不能邀请好友");
                            return;
                        }
                        InviteFriendFragment.newInstance(gameDetailBean)
                                .setSize(278, 326)
                                .show(getSupportFragmentManager());
                        break;

                }
                break;
            case R.id.in_shop:
                if (gameDetailBean != null && !TextUtils.isEmpty(gameDetailBean.getShopId()))
                    BusinessDetailActivity.start(this,
                            gameDetailBean.getId(), gameDetailBean.getShopId(),
                            gameDetailBean.getEmchatId(), false);
                else if (gameDetailBean != null && TextUtils.isEmpty(gameDetailBean.getShopId())
                        && TextUtils.equals(gameDetailBean.getUserId(), UserMgr.getInstance().getLoginUser().getUid())) {
                    ChoseBusinessActivity.start(this, playId, this.gameDetailBean.getPlayType(), gameDetailBean.getId(), gameDetailBean.getEmchatId());
                }
                break;
            default:
                break;
        }
    }

    final boolean[] jubenCheck = {false};
    final boolean[] shopCheck = {false};

    //  选择商家or剧本-----评论
    private void judgeDialogShow() {
        judgeDialog.show();
        jubenCheck[0] = false;
        shopCheck[0] = false;
        //  选择剧本评价
        if (gameDetailBean.getResponsePlay() == 0) {
            tv_judge_juben.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (jubenCheck[0]) {
                        tv_judge_juben.setCompoundDrawables(null, null, uncheck, null);
                    } else {
                        tv_judge_juben.setCompoundDrawables(null, null, check, null);
                        if (gameDetailBean.getResponseShop() == 0) {

                            shopCheck[0] = false;
                            tv_judge_shop.setCompoundDrawables(null, null, uncheck, null);
                        }
                    }
                    jubenCheck[0] = !jubenCheck[0];
                }
            });
        } else {
            tv_judge_juben.setText("剧本（已评论）");
            tv_judge_juben.setCompoundDrawables(null, null, null, null);
            tv_judge_juben.setClickable(false);
        }
        // 选择商家评论
        if (gameDetailBean.getResponseShop() == 0) {
            tv_judge_shop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (shopCheck[0]) {
                        tv_judge_shop.setCompoundDrawables(null, null, uncheck, null);
                    } else {
                        tv_judge_shop.setCompoundDrawables(null, null, check, null);
                        if (gameDetailBean.getResponsePlay() == 0) {
                            jubenCheck[0] = false;
                            tv_judge_juben.setCompoundDrawables(null, null, uncheck, null);
                        }
                    }
                    shopCheck[0] = !shopCheck[0];
                }
            });
        } else {
            tv_judge_shop.setText("商家（已评论）");
            tv_judge_shop.setCompoundDrawables(null, null, null, null);
            tv_judge_shop.setClickable(false);
        }
        // 确定按钮
        tv_judge_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                judgeDialog.dismiss();
                scoreDialog.show();

            }
        });
        //取消按钮
        tv_judge_cancel.setOnClickListener(view -> {
            judgeDialog.dismiss();
        });
    }

    @Override
    public void setGDetail(GameDetailResponse gameDetailBean) {
        this.gameDetailBean = gameDetailBean;
        String str = gameDetailBean.getPayedNum() + " / " + gameDetailBean.getNeedNum();
        SpannableStringBuilder stringBuilder = SpannableStringUtil.changeTextColor(str, Color.parseColor("#FABE00"), 0, 1);
        tvCount.setText(stringBuilder);
        tv_time.setText(gameDetailBean.getGameTime());
        tvName.setText(gameDetailBean.getTeamName());
        tvGroupNo.setText(gameDetailBean.getOrderNumber());//队伍编号
        tvNickName.setText(gameDetailBean.getCaptainName());
        tvBusName.setText(gameDetailBean.getShop().getName());
        tvAddress.setText(gameDetailBean.getShop().getLocation());
        tvType.setText(gameDetailBean.getTypeName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvIntroduce.setText(Html.fromHtml(gameDetailBean.getPlayDesc().replace("\n", "<br>"), FROM_HTML_MODE_COMPACT));
        } else {
            tvIntroduce.setText(Html.fromHtml(gameDetailBean.getPlayDesc().replace("\n", "<br>")));
        }
        ImageLoader.loadRoundCorners(this, gameDetailBean.getPlayImage(), ivImg, 5);
        ImageLoader.loadCircleHead(this, gameDetailBean.getShop().getPhoto(), ivHead);
        if (TextUtils.isEmpty(gameDetailBean.getShopId())) {
            tv_empty_place.setVisibility(View.VISIBLE);
            group_business_msg.setVisibility(View.GONE);
        } else {
            tv_empty_place.setVisibility(View.GONE);
            group_business_msg.setVisibility(View.VISIBLE);
            tvSHopName.setText(gameDetailBean.getShop().getName());
            tvLevel.setText("LV." + gameDetailBean.getShop().getLevel());
        }
        ConstraintLayout viewById = findViewById(R.id.in_shop);
        group_business_msg.updatePreLayout(viewById);

        playId = gameDetailBean.getPlayId();
        //组队成员

        mMemberAdapter.setDatas(new ArrayList<>(gameDetailBean.getUsers()));
        users = gameDetailBean.getUsers();
        tvMembers.setText("组队成员(" + users.size() + ")");

        // 剧本评分
        tvScore.setText(gameDetailBean.getPlayScole() + "");
        rbvStar.setStar(Math.round(gameDetailBean.getPlayScole()), false);
        tvTotalComment.setText(gameDetailBean.getPlayCount() + "次评论");
        if (1 == gameDetailBean.getIsNeedPlay()) {
            rvRole.setVisibility(View.VISIBLE);
            tv_role_title.setVisibility(View.VISIBLE);
            mScriptDetailPresenter.getScriptRole(playId);
        }
        showChatIcon(gameDetailBean);
    }

    private void showChatIcon(GameDetailResponse gameDetailBean) {
        if (gameDetailBean == null)
            return;
        String uid = UserMgr.getInstance().getLoginUser().getUid();
        for (GameDetailResponse.UsersBean user : gameDetailBean.getUsers()) {
            if (TextUtils.equals(uid, user.getUid())) {
                tvGonChat.setVisibility(View.VISIBLE);
                break;
            }
        }
    }


    private void onArrowClick() {
        if (isOpen) {
            isOpen = false;
            tvIntroduce.setMaxLines(3);
            ivOpenClose.setRotation(0);
        } else {
            isOpen = true;
            tvIntroduce.setMaxLines(Integer.MAX_VALUE);
            ivOpenClose.setRotation(180);
        }
    }


    // 组队成员
    private void initMemberRv() {
        rvMembers.setLayoutManager(new LinearLayoutManager(this));
        mMemberAdapter = new RVAdapter<>(new GroupMemberItem());
        rvMembers.setAdapter(mMemberAdapter);
        mMemberAdapter.setOnItemClickListener((view, position) -> {
            Object data = mMemberAdapter.getData(position);
            if (data instanceof GameDetailResponse.UsersBean) {
                GameDetailResponse.UsersBean bean = (GameDetailResponse.UsersBean) data;
                MemberMsgActivity.start(GameDetailsActivity.this, bean.getUid(), "");
            }
        });
    }

    private void initCommentRv() {
        rvComment.setLayoutManager(new LinearLayoutManager(this));
        mCommentAdapter = new RVAdapter<>(new GameCommentView());
        rvComment.setAdapter(mCommentAdapter);
    }

    private void initRvRole() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvRole.setLayoutManager(linearLayoutManager);
        mRoleAdapter = new RVAdapter<>(new RoleItem());
        rvRole.setAdapter(mRoleAdapter);
        mRoleAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                gotoRolePagerActivity(position);
            }
        });
    }

    private void gotoRolePagerActivity(int pos) {
        ArrayList<ScriptRoleBean> roleBeans = (ArrayList<ScriptRoleBean>) mRoleAdapter.getDatas();
        RolePagerActivity.start(this, roleBeans, pos);
    }

    @Override
    public void setCommentData(List<CommentBean> commentBeans, int totalPage) {
        List<Object> datas = mCommentAdapter.getDatas();
        datas.addAll(new ArrayList<>(commentBeans));
        mCommentAdapter.notifyDataSetChanged();
        if (page >= totalPage) {
            mRefresh.setEnableLoadMore(false);
        }
    }

    @Override
    public void setScriptDetail(ScriptDetailResponse response) {

    }

    @Override
    public void setScriptRole(List<ScriptRoleBean> roleBeans) {
        mRoleAdapter.setDatas(roleBeans);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void submitPlaySuccess() {
        gameDetailBean.setResponsePlay(1);
        if (scoreDialog != null && scoreDialog.isShowing())
            scoreDialog.dismiss();
    }

    @Override
    public void submitShopSuccess() {
        gameDetailBean.setResponseShop(1);
        if (scoreDialog != null && scoreDialog.isShowing())
            scoreDialog.dismiss();
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    @Subscribe
    public void onGroupChangeEvent(ChangeGroupEvent event) {
        gameDetailPresenter.getGameDetail(id);
    }
}
